<?php

namespace App\Http\Controllers;

use App\Models\Material;
use App\Models\InventoryRecord;
use App\Models\OperationLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class InventoryController extends Controller
{
    /**
     * 构造函数，设置中间件
     */
    public function __construct()
    {
        $this->middleware('auth');
        // 只有管理员可以执行出入库操作
        $this->middleware('role:admin')->only(['createIn', 'createOut', 'storeIn', 'storeOut']);
    }

    /**
     * 显示出入库记录列表
     */
    public function index(Request $request)
    {
        $query = InventoryRecord::with(['material', 'user'])
            ->select('inventory_records.*', 'users.username')
            ->leftJoin('users', 'inventory_records.user_id', '=', 'users.id');

        // 搜索条件
        if ($request->filled('material_id')) {
            $query->where('material_id', $request->material_id);
        }
        if ($request->filled('type')) {
            $query->where('type', $request->type);
        }
        if ($request->filled('date_start')) {
            $query->whereDate('created_at', '>=', $request->date_start);
        }
        if ($request->filled('date_end')) {
            $query->whereDate('created_at', '<=', $request->date_end);
        }
        if ($request->filled('user_id')) {
            $query->where('user_id', $request->user_id);
        }

        $records = $query->orderBy('created_at', 'desc')->paginate(10);
        $materials = Material::all();
        $users = DB::table('users')->select('id', 'username')->get();

        return view('inventory.index', compact('records', 'materials', 'users'));
    }

    /**
     * 显示创建出入库记录表单
     */
    public function create()
    {
        $materials = Material::all();
        return view('inventory.create', compact('materials'));
    }

    public function createIn()
    {
        $materials = Material::all();
        return view('inventory.create_in', compact('materials'));
    }

    public function createOut()
    {
        $materials = Material::all();
        return view('inventory.create_out', compact('materials'));
    }

    /**
     * 保存出入库记录
     */
    public function storeIn(Request $request)
    {
        $request->validate([
            'material_id' => 'required|exists:materials,id',
            'quantity' => 'required|numeric|min:0.01',
            'remark' => 'nullable|string'
        ]);

        DB::transaction(function () use ($request) {
            $material = Material::findOrFail($request->material_id);
            $material->increment('quantity', $request->quantity);

            $record = InventoryRecord::create([
                'material_id' => $request->material_id,
                'type' => 1,
                'quantity' => $request->quantity,
                'user_id' => Auth::id(),
                'remark' => $request->remark
            ]);

            OperationLog::create([
                'user_id' => Auth::id(),
                'action' => 'create',
                'target_type' => 'inventory',
                'target_id' => $record->id,
                'content' => "入库：{$material->name} {$request->quantity}{$material->unit}",
                'ip' => $request->ip()
            ]);
        });

        return redirect()->route('inventory.index')->with('success', '入库成功');
    }

    /**
     * 处理出库操作
     */
    public function storeOut(Request $request)
    {
        $request->validate([
            'material_id' => 'required|exists:materials,id',
            'quantity' => 'required|numeric|min:0.01',
            'remark' => 'nullable|string|max:255'
        ]);

        $material = Material::findOrFail($request->material_id);

        // 检查库存是否足够
        if ($material->quantity < $request->quantity) {
            return response()->json([
                'success' => false,
                'message' => "库存不足！当前库存: {$material->quantity} {$material->unit}"
            ]);
        }

        DB::transaction(function () use ($request, $material) {
            // 创建出库记录
            $record = InventoryRecord::create([
                'material_id' => $request->material_id,
                'type' => 2, // 出库
                'quantity' => $request->quantity,
                'user_id' => Auth::id(),
                'remark' => $request->remark
            ]);

            // 更新库存
            $material->decrement('quantity', $request->quantity);

            // 记录操作日志
            OperationLog::create([
                'user_id' => Auth::id(),
                'action' => 'out',
                'target_type' => 'material',
                'target_id' => $material->id,
                'content' => "出库：{$material->name} {$request->quantity} {$material->unit}",
                'ip' => $request->ip()
            ]);
        });

        return response()->json([
            'success' => true,
            'message' => '出库成功'
        ]);
    }

    /**
     * 导出出入库记录
     */
    public function export()
    {
        $records = InventoryRecord::with(['material', 'user'])
            ->orderBy('created_at', 'desc')
            ->get();
        
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="inventory_records.csv"',
        ];

        $callback = function() use ($records) {
            $file = fopen('php://output', 'w');
            
            // 添加 UTF-8 BOM
            fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));
            
            // 添加表头
            fputcsv($file, ['ID', '材料', '类型', '数量', '操作人', '备注', '时间']);
            
            // 添加数据
            foreach ($records as $record) {
                fputcsv($file, [
                    $record->id,
                    $record->material->name,
                    $record->type == 1 ? '入库' : '出库',
                    $record->quantity,
                    $record->user->username,
                    $record->remark,
                    $record->created_at
                ]);
            }
            
            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }

    /**
     * 显示出入库统计
     */
    public function statistics()
    {
        // 获取最近30天的出入库统计
        $dailyStats = InventoryRecord::select(
            DB::raw('DATE(created_at) as date'),
            DB::raw('SUM(CASE WHEN type = 1 THEN quantity ELSE 0 END) as in_quantity'),
            DB::raw('SUM(CASE WHEN type = 2 THEN quantity ELSE 0 END) as out_quantity')
        )
        ->where('created_at', '>=', now()->subDays(30))
        ->groupBy('date')
        ->get();

        // 获取材料类型统计
        $typeStats = Material::select('types.name', DB::raw('COUNT(*) as count'))
            ->join('types', 'materials.type_id', '=', 'types.id')
            ->groupBy('types.id', 'types.name')
            ->get();

        return view('inventory.statistics', compact('dailyStats', 'typeStats'));
    }
}
